package com.wen.mall.service.impl;

import com.wen.mall.dao.UserDao;
import com.wen.mall.enums.RoleEnum;
import com.wen.mall.pojo.User;
import com.wen.mall.service.UserService;
import com.wen.mall.vo.ResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.Date;

import static com.wen.mall.enums.ResponseEnum.*;

/**
 * @author 温嘉璐
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    UserDao userDao;

    /**
     * 注册
     *
     * @param user 根据user查询
     * @return
     */
    @Override
    public ResponseVo register(User user) {


        //用户名不能重复
        Integer countByUsername = userDao.countByUsername(user);
        if (countByUsername > 0) {
            return ResponseVo.error(USERNAME_EXISTS);
        }
        //email不能重复
        Integer countByEmail = userDao.countByEmail(user);
        if (countByEmail > 0) {

            return ResponseVo.error(EMAIL_EXISTS);
        }
        //密码使用MD5加密
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8)));
        user.setRole(RoleEnum.CUSTOMER.getCode());
        user.setUpdateTime(new Date());
        user.setCreateTime(new Date());
        Integer resultCount = userDao.insert(user);
        if (resultCount == 0) {
            return ResponseVo.error(ERROR);
        }

        return ResponseVo.success();

    }

    @Override
    public ResponseVo<User> login(User user) {
        User byUsername = userDao.findByUsername(user);

        if (byUsername == null) {
            return ResponseVo.error(USER_PASSWORD_ERROR);
        }

        if (!byUsername.getPassword().equalsIgnoreCase(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()))) {
            return ResponseVo.error(USER_PASSWORD_ERROR);
        }
        byUsername.setPassword(null);

        return ResponseVo.success(byUsername);
    }


}
